package com.keli.dt.algorithm;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;


public class ZhoushanRoadInfo extends RoadInfo {
	/** 键值对：key:道路等级, value:参数(F, x, y, z, p, k) */
	public static final Map<Integer, int[]> TYPE2PARAMS;
	
	public static final double ERROR_CODE = -1;
	
	private Logger log = Logger.getLogger(getClass());
	
	static {
		TYPE2PARAMS = new HashMap<Integer, int[]>();
		TYPE2PARAMS.put(new Integer(5), new int[]{80, 15, 30, 45, 55, 80});
		TYPE2PARAMS.put(new Integer(6), new int[]{60, 15, 25, 35, 45, 60});
		TYPE2PARAMS.put(new Integer(7), new int[]{40, 5, 15, 25, 30, 40});
		TYPE2PARAMS.put(new Integer(8), new int[]{35, 5, 10, 20, 25, 35});
	}

	@Override
	public double calcTPI(double speed, int roadType) {
		double vf = getFreeflowSpeed(roadType);
		if (vf == 0) {
			return ERROR_CODE;	// 道路等级未找到出错
		}
		
		if (speed > vf) {
			return 0;
		}
		
		int[] param = TYPE2PARAMS.get(roadType);
		if (param == null) {
			log.error("Not found param with type: " + roadType);
			return ERROR_CODE;	// 道路等级未找到出错
		}
		
		double a = (vf - speed) / vf * param[0];
		
		return calcTPI(a, param);
	}
	
	private double calcTPI(double a, int[] param) {
		double tpi;
		if (a >= param[param.length - 1]) {
			tpi = 10;
		} else {
			int i = find(a, param);
			if (i == -1) {
				return ERROR_CODE;	// a越界出错
			} else {
				double m = param[i];
				double n = (i == 1 ? 0 : param[i - 1]);
				tpi = 2 * (i - 1) + (a - n) / (m - n) * 2;
			}
		}
		
		return tpi;
	}
	
	/**
	 * 查找最接近的上限
	 * @param a 参数a
	 * @param param 递增上限数组
	 * @return 未找到返回-1
	 */
	private int find(double a, int[] param) {
		// 下标从1开始对应的数字为x, y, z, p, k
		for (int i = 1; i < param.length; i++) {
			if (a <= param[i]) {
				return i;
			}
		}
		log.error("not found proper params in [x, y, z, p, k]");
		return -1;
	}

}
